from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
from baidubce.services.bos.bos_client import BosClient


def upload(key, data, bucket_name="image-home"):
    #设置BosClient的Host，Access Key ID和Secret Access Key
    bos_host = "bj.bcebos.com"
    access_key_id = "d7b0528d41804aca885b7ad4cd189d78"
    secret_access_key = "e63ec63116ee41ffbb0d11e652e14f18"

    #创建BceClientConfiguration
    config = BceClientConfiguration(credentials=BceCredentials(access_key_id, secret_access_key), endpoint=bos_host)

    # 创建上传客户端
    client = BosClient(config)

    response = client.put_object_from_string(bucket=bucket_name, key=key, data=data)

    access_url = "http://" + bucket_name + "." + bos_host + "/" + key

    return access_url


if __name__ == '__main__':
    filename = "dj_2.jpg"
    try:
        with open(filename, "rb") as fp:
            data = fp.read()
            access_url = upload(key=filename, data=data)
    except Exception as e:
        print(e)
    else:
        print(access_url)